import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

class CameraPage extends StatefulWidget {
  @override
  _CameraPageState createState() => _CameraPageState();
}

class _CameraPageState extends State<CameraPage> {
  CameraController _controller;
  String path;
  GlobalKey _imgKey = GlobalKey();
  GlobalKey _borderKey = GlobalKey();
  Uint8List pngBytes;

  @override
  void initState() {
    super.initState();
    initControl();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FlatButton(
        onPressed: () async {
          Directory tempDir = await getTemporaryDirectory();
          var curTime = DateTime.now().millisecondsSinceEpoch;
          String tempPath = "${tempDir.path}/auth_$curTime.png";
          File f = File(tempPath);
          bool exits = await f.exists();
          if (exits) {
            await f.delete();
          }
          await _controller.takePicture(tempPath);
          path = tempPath;
          RenderBox imgBox = _imgKey.currentContext.findRenderObject();
          var offset = imgBox.localToGlobal(Offset.zero);
          Rect imgRect = Rect.fromLTWH(
              offset.dx, offset.dy, imgBox.size.width, imgBox.size.height);
          RenderBox borderBox = _borderKey.currentContext.findRenderObject();
          var borderOffset = borderBox.localToGlobal(Offset.zero);
          Rect borderRect = Rect.fromLTWH(borderOffset.dx, borderOffset.dy,
              borderBox.size.width, borderBox.size.height);
          String result = await CutUtil.cutImg(path, imgRect, borderRect);
          Navigator.push(context, MaterialPageRoute(builder: (ctx) {
            return PicPage(result);
          }));
        },
        child: Icon(Icons.camera_alt),
      ),
      body: Stack(
        children: [
          Container(
            key: _imgKey,
            child: buildBody(),
          ),
          Positioned(
            child: Center(
              child: SizedBox(
                key: _borderKey,
                width: 300,
                child: AspectRatio(
                  aspectRatio: 54 / 85.6,
                  child: Container(
                    decoration:
                        BoxDecoration(border: Border.all(color: Colors.blue)),
                  ),
                ),
              ),
            ),
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
          ),
        ],
      ),
    );
  }

  Widget buildBody() {
    if (_controller == null) {
      return Container();
    }
    if (!_controller.value.isInitialized) {
      return Container();
    }
    return _controller != null
        ? AspectRatio(
            aspectRatio: _controller.value.aspectRatio,
            child: path != null
                ? Image.file(File(path))
                : CameraPreview(_controller),
          )
        : Container();
  }

  void initControl() async {
    List<CameraDescription> cameras = await availableCameras();
    _controller = CameraController(cameras[0], ResolutionPreset.high);
    await _controller.initialize();
    print("测试一下：${_controller.value.aspectRatio}");
    setState(() {});
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

class CutUtil {
  static MethodChannel _channel = MethodChannel("sl.cutAuthImage");

  static Future<String> cutImg(
      String path, Rect imgRect, Rect borderRect) async {
    var resultPath = await _channel.invokeMethod("cutAuth", {
      "path": path,
      "imgViewCutRectStartX": imgRect.left,
      "imgViewCutRectStartY": imgRect.top,
      "imgViewCutRectWidth": imgRect.width,
      "imgViewCutRectHeight": imgRect.height,
      "borderViewCutRectStartX": borderRect.left,
      "borderViewCutRectStartY": borderRect.top,
      "borderViewCutRectWidth": borderRect.width,
      "borderViewCutRectHeight": borderRect.height,
    });
    print(resultPath);
    return resultPath.toString();
  }
}

class PicPage extends StatelessWidget {
  String path;

  PicPage(this.path);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Image.file(File(path),),
      ),
    );
  }
}
